﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Data.OleDb;
using System.Configuration;

namespace WeakEndForum
{
    public partial class MasterPage : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Modules.isUserConnected())
            {
                lblActiveUser.Text = Modules.getConnectedUser();
                imgAvatarUser.ImageUrl = (string)Session["Image_Avatar"];
            }

            if (Modules.isAdmin(Modules.getConnectedUser()))
            {
               
            }
        }

        protected void loginForm_ServerValidate(object source, ServerValidateEventArgs args)
        {
            byte[] sel;
            byte[] truePassword;
            byte[] createdPass;
            args.IsValid = false;
            string enteredEmail = txtEmail.Text;


            OleDbConnection connection = new OleDbConnection(ConfigurationManager.ConnectionStrings[Constantes.DB_NAME].ConnectionString);
            connection.Open();
            OleDbCommand verifyUser = new OleDbCommand("SELECT Username, [Password], Sel, Image_Avatar FROM Utilisateurs WHERE Email = @email", connection);
            verifyUser.Parameters.Add(new OleDbParameter("email", enteredEmail) { OleDbType = OleDbType.VarChar, Size = 255 });
            verifyUser.Prepare();

            OleDbDataReader dataReader = verifyUser.ExecuteReader();


            if (dataReader.Read())
            {
                truePassword = (byte[])dataReader[1];
                sel = (byte[])dataReader[2];

                Rfc2898DeriveBytes hachoir = new Rfc2898DeriveBytes(txtPassword.Text, sel, 1500);
                createdPass = hachoir.GetBytes(24);

                if (truePassword.SequenceEqual(createdPass))
                {
                    if (!Modules.isBan((string)dataReader[0]))
                    {
                        Session["Username"] = dataReader[0];
                        Session["Image_Avatar"] = @"User_Data\images\" + dataReader[3];
                        args.IsValid = true;
                    }
                    else
                    {
                        Response.Redirect("Banned.aspx");
                        args.IsValid = true;
                    }
                }
            }
            connection.Close();
            if (args.IsValid)
            {
                Response.Redirect("Default.aspx");
            }
        }

        protected void btnDeconnect_Click(object sender, EventArgs e)
        {
            Session.Abandon();
            Response.Redirect("Default.aspx");
        }

        protected bool isAdmin()
        {
            return Modules.isAdmin(Modules.getConnectedUser());
        }
    }
}